package com.agileai.esb.smc.controller;

import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.esb.smc.bizmoduler.sysres.SkAppManage;
import com.agileai.esb.smc.domain.Function;
import com.agileai.esb.smc.domain.User;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.domain.TreeBuilder;
import com.agileai.hotweb.domain.TreeModel;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.StringUtil;
/**
 * 功能菜单处理类
 * @author zhang_ji_yu@163.com
 */
public class MenuTreeHandler extends BaseHandler{
	public static final String FUNC_ID_TAG = "funcId";
	
	public static final String APP = "app";
	public static final String MF = "mf";
	public static final String WS = "ws";
	public static final String WSFOLDER = "wsfolder";
	public static final String MFFOLDER = "mffolder";
	
	public MenuTreeHandler(){
		super();
	}
	
	public ViewRenderer prepareDisplay(DataParam param){
		User user = (User)this.getUser();
		String refreshTree =  (String)this.getSessionAttribute("refreshTree");
		if ("Y".equals(refreshTree) || "Y".equals(param.get("refreshTree"))){
			this.removeSessionAttribute("refreshTree");
			this.initFuncList8Map(user);
		}
		List<Function> funcList = user.getFuncList();

		String menuTreeSyntax = this.getTreeSyntax(funcList,new StringBuffer());
		this.setAttribute("menuTreeSyntax", menuTreeSyntax);
		return new LocalRenderer(getPage());
	}
	
	private void initFuncList8Map(User user) {
		user.getFuncMap().clear();
		user.getFuncList().clear();
		SkAppManage skAppManage = this.lookupService(SkAppManage.class);
		List<DataRow> records = skAppManage.findTreeRecords(user.getUserId());
		for (int i=0;i < records.size();i++){
			DataRow row = records.get(i);
			Function function = new Function();
			String funcId = row.stringValue("FUNC_ID");
			function.setFuncId(funcId);
			function.setFuncName(row.stringValue("FUNC_NAME"));
			function.setFuncPid(row.stringValue("FUNC_PID"));
			function.setFuncUrl(row.stringValue("FUNC_URL"));
			function.setFuncType(row.stringValue("FUNC_TYPE"));
			user.getFuncList().add(function);
			user.getFuncMap().put(funcId, function);
		}
	}	
	
	private String getTreeSyntax(List<Function> funcRecords,StringBuffer treeSyntax){
    	String result = null;
    	try {
    		treeSyntax.append("<script type='text/javascript'>");
    		treeSyntax.append("d = new dTree('d');");
    		TreeBuilder treeBuilder = new TreeBuilder(funcRecords,"funcId","funcName","funcPid");
    		treeBuilder.setTypeKey("funcType");
    		treeBuilder.setPojoList(true);
            TreeModel treeModel = treeBuilder.buildTreeModel();
            String rootFuncId = treeModel.getId();
            String rootFuncName = treeModel.getName();
            treeSyntax.append("d.add('"+rootFuncId+"',-1,'"+rootFuncName+"',null);");
            treeSyntax.append("\r\n");
            buildTreeSyntax(treeSyntax,treeModel);
            treeSyntax.append("\r\n");
            treeSyntax.append("document.write(d);");
            treeSyntax.append("\r\n");
    		treeSyntax.append("</script>");
    		result = treeSyntax.toString();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
    }
	
	private void buildTreeSyntax(StringBuffer treeSyntax,TreeModel treeModel){
		List<TreeModel> children = treeModel.getChildren();
		String parentId = treeModel.getId();
        for (int i=0;i < children.size();i++){
        	TreeModel child = children.get(i);
            String curFuncId = child.getId();
            String curFuncName = child.getName();
        	if (APP.equals(child.getType())){
            	treeSyntax.append("d.add('"+curFuncId+"','"+parentId+"','"+curFuncName+"','javascript:showFunction(\\\'"+curFuncId+"\\\')',null,null,'images/dtree/project.gif','images/dtree/project.gif');");
            	treeSyntax.append("\r\n");
        	}
        	else if (WSFOLDER.equals(child.getType())){
            	treeSyntax.append("d.add('"+curFuncId+"','"+parentId+"','"+curFuncName+"','javascript:showFunction(\\\'"+curFuncId+"\\\')',null,null,'images/dtree/wsfolder.png','images/dtree/wsfolder.png');");
            	treeSyntax.append("\r\n");
        	}
        	else if (MFFOLDER.equals(child.getType())){
            	treeSyntax.append("d.add('"+curFuncId+"','"+parentId+"','"+curFuncName+"','javascript:showFunction(\\\'"+curFuncId+"\\\')',null,null,'images/dtree/mffolder.png','images/dtree/mffolder.png');");
            	treeSyntax.append("\r\n");
        	}
        	else if ("funcmenu".equals(child.getType())){
            	treeSyntax.append("d.add('"+curFuncId+"','"+parentId+"','"+curFuncName+"',null,null,null,'images/dtree/custfolder.gif','images/dtree/custfolder.gif');");
            	treeSyntax.append("\r\n");     		
        	}
        	else if (MF.equals(child.getType())){
            	treeSyntax.append("d.add('"+curFuncId+"','"+parentId+"','"+curFuncName+"','javascript:showFunction(\\\'"+curFuncId+"\\\')',null,null,'images/dtree/mf.gif','images/dtree/mf.gif');");
            	treeSyntax.append("\r\n");
        	}
        	else if (WS.equals(child.getType())){
            	treeSyntax.append("d.add('"+curFuncId+"','"+parentId+"','"+curFuncName+"','javascript:showFunction(\\\'"+curFuncId+"\\\')',null,null,'images/dtree/service.png','images/dtree/service.png');");
            	treeSyntax.append("\r\n");
        	}
        	else{
            	treeSyntax.append("d.add('"+curFuncId+"','"+parentId+"','"+curFuncName+"','javascript:showFunction(\\\'"+curFuncId+"\\\')',null,null,'images/dtree/node.gif','images/dtree/node.gif');");
            	treeSyntax.append("\r\n");            		
        	}
            this.buildTreeSyntax(treeSyntax,child);
        }
    }
	@PageAction
	public ViewRenderer showFunction(DataParam param){
		String funcId = param.get(FUNC_ID_TAG);
		User user = (User)getUser();
		Function function = user.getFuncMap().get(funcId);
		user.setCurrentFuncId(funcId);
		String handlerURL = null;
		String funcURL = function.getFuncUrl();
//    	if (MF.equals(function.getFuncType())){
//    		handlerURL = funcURL + "&fromNode=true";
//    	}
//    	else if (WS.equals(function.getFuncType())){
//    		handlerURL = funcURL + "&fromNode=true"; 
//    	}
//    	else{
    		handlerURL = funcURL;
//    	}
		//do reset Param Session Trace
		this.getSessionAttributes().remove(PARAM_TRACE);
		StringBuffer responseText = new StringBuffer();
		StringBuffer script = new StringBuffer();
		script.append("parent.mainFrame.location.href='").append(handlerURL).append("';");
		String currentVisitPath = this.buildCurrentPath(function);
		script.append("parent.topright.document.getElementById('currentPath').innerHTML=\"").append(currentVisitPath).append("\";");
		responseText.append(script);
		return new AjaxRenderer(responseText.toString());
	}
	
	private String buildCurrentPath(Function function){
		String result = null;
		StringBuffer path = new StringBuffer();
		
		String funcURL = function.getFuncUrl();
		String funcName = function.getFuncName();
		path.append("<a href=javascript:showPage('").append(funcURL).append("')>").append(funcName).append("</a>");
		
		String funcParentId = function.getFuncPid();
		if (!StringUtil.isNullOrEmpty(funcParentId)){
			User user = (User)getUser();
			Function parent = user.getFuncMap().get(funcParentId);
			if (parent != null){
				this.uploopMenuItem(path,parent);
			}			
		}
		result = path.toString();
		return result;
	}
	
	private void uploopMenuItem(StringBuffer path,Function function ){
		StringBuffer temp = new StringBuffer();
		if (StringUtil.isNullOrEmpty(function.getFuncUrl())){
			temp.append(function.getFuncName()).append("&nbsp;-->&nbsp;");
		}else{
			temp.append("<a href=javascript:showPage('").append(function.getFuncUrl()).append("')>").append(function.getFuncName()).append("</a> &nbsp; --> &nbsp;");			
		}
		path.insert(0, temp.toString());
		String funcParentId = function.getFuncPid();
		if (!StringUtil.isNullOrEmpty(funcParentId)){
			User user = (User)getUser();
			Function parent = user.getFuncMap().get(funcParentId);
			this.uploopMenuItem(path,parent);
		}
	}
}
